/**
 * 
 */
package com.winit.openapi.fsp.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.spi.context.CommandContext;
import com.winit.fsp.spi.supplier.SupplierService;
import com.winit.fsp.spi.supplier.command.CreateSupplierCommand;
import com.winit.fsp.spi.supplier.command.FindSupplierContactBySupplierIdCommand;
import com.winit.fsp.spi.supplier.command.FindSupplierFileBySupplierIdCommand;
import com.winit.fsp.spi.supplier.command.GetSupplierByIdCommand;
import com.winit.fsp.spi.supplier.command.QuerySupplierByCustomerIdCommand;
import com.winit.fsp.spi.supplier.command.UpdateSupplierCommand;
import com.winit.fsp.spi.supplier.vo.Supplier;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * fsp 供应商处理
 * 
 * @author
 * @since 1.0
 */
@Controller
@RequestMapping(value = "/fsp/supplier")
public class SupplierController extends BaseController {

    @Resource
    private SupplierService supplierService;

    /**
     * 创建fsp供应商
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/create")
    public String create(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        CreateSupplierCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            try {
                command = JSONObject.parseObject(json.toJSONString(), CreateSupplierCommand.class);
            } catch (Exception e) {
                throw new ApiException(ErrorCode.ILLEGAL_JSON_STRING, e.getMessage());
            }
            
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

//        CommandContext ctx = CommandContext.getContext();
//        Bpartner bpartner = (Bpartner) ctx.get(ApiConstant.API_BPARTNER);
        // command.setCustomerId(bpartner.getcBpartnerId().intValue());
        Long id = supplierService.createSupplier(command);
        responseMsg.setData(id);
        return SUCCESS;
    }

    /**
     * 修改fsp资信申请
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/update")
    public String update(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        UpdateSupplierCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            try {
                command = JSONObject.parseObject(json.toJSONString(), UpdateSupplierCommand.class);
            } catch (ApiException e) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, e.getMessage());
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        // 调用接口更新信息
        supplierService.updateSupplier(command);
        return SUCCESS;
    }

    /**
     * 查询fsp资信详情
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/query")
    public String query(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GetSupplierByIdCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            command = buildQuerySupplierInfoCommand(json);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Supplier supplier = supplierService.getSupplierById(command);

        FindSupplierContactBySupplierIdCommand fscc = new FindSupplierContactBySupplierIdCommand();
        CommandContext ctx = CommandContext.getContext();
        fscc.setCtx(ctx);
        fscc.setSupplierId(command.getSupplierId());
        supplier.setSupplierContactList(this.supplierService.findSupplierContactBySupplierId(fscc));

        FindSupplierFileBySupplierIdCommand fsfc = new FindSupplierFileBySupplierIdCommand();
        fsfc.setCtx(ctx);
        fsfc.setSupplierId(command.getSupplierId());
        supplier.setSupplierFileList(this.supplierService.findSupplierFileBySupplierId(fsfc));
        responseMsg.setData(supplier);

        return SUCCESS;
    }

    /**
     * 查询供应商列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();

        QuerySupplierByCustomerIdCommand command = null;

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            validpageParams(json);
            command = new QuerySupplierByCustomerIdCommand();
            if (json.containsKey("customerId")) {
                command.setCustomerId(json.getLong("customerId"));
            }
            Searchable searchable = buildSearchPageParams(json);
            command.setSearchable(searchable);
        } else if (obj == null || StringUtils.isBlank(obj.toString())) {
            Searchable searchable = buildSearchPageParams(null);
            command = new QuerySupplierByCustomerIdCommand();
            command.setSearchable(searchable);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        // 调用接口分页查询订单
        Page<Supplier> pagelist = supplierService.querySupplierByCustomerId(command);
        if (pagelist != null) {

            Map<String, Object> pageMap = new HashMap<String, Object>();
            pageMap.put("pageNo", pagelist.getPageable().getPageNumber() + 1);
            pageMap.put("pageSize", pagelist.getPageable().getPageSize());
            pageMap.put("totalCount", pagelist.getTotalElements());

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", pagelist.content);
            data.put("pageParams", pageMap);
            responseMsg.setData(data);
        }

        return SUCCESS;
    }

    private void validpageParams(JSONObject json) {
        // pageParams
        if (json.containsKey("pageParams")) {
            Object obj = json.get("pageParams");
            if (obj instanceof JSONObject) {
                JSONObject pageParams = (JSONObject) obj;
                // pageNo
                ValidateUtil.validInteger(pageParams, "pageNo");

                // pageSize
                ValidateUtil.validInteger(pageParams, "pageSize");

                if (pageParams.containsKey("pageNo")) {
                    int pageNo = pageParams.getInteger("pageNo");
                    if (pageNo < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                    }
                }
                if (pageParams.containsKey("pageSize")) {
                    int pageSize = pageParams.getInteger("pageSize");
                    if (pageSize < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                    }
                }
            } else {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageParams");
            }
        }
    }

    private Searchable buildSearchPageParams(JSONObject json) {
        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        // pageParams
        if (json != null && json.containsKey("pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");
            // pageNo
            if (pageParams.containsKey("pageNo")) {
                pageNo = pageParams.getInteger("pageNo");
            }
            // pageSize
            if (pageParams.containsKey("pageSize")) {
                pageSize = pageParams.getInteger("pageSize");
            }
        }
        Searchable search = Searchable.newSearchable();
        search.setPage(pageNo - 1, pageSize);

        // search.addSort(new Sort(Direction.DESC, "CREATED"));

        return search;
    }

    private GetSupplierByIdCommand buildQuerySupplierInfoCommand(JSONObject json) {
        GetSupplierByIdCommand command = new GetSupplierByIdCommand();
        if (json.containsKey("Id")) {
            command.setSupplierId(json.getLong("Id"));
        }
        CommandContext ctx = CommandContext.getContext();
        command.setCtx(ctx);
        return command;
    }

}
